//
//  LoginViewController.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/2/26.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

enum LoginType {
    case login  //登录
    case rigist //注册
    case changePsd  //修改密码
}

let LoginViewControllerNotification = "LoginViewControllerNotification"

let LoginViewControllerSuccessKey = "isSuccess"
typealias AccountCompelteHandle = (_ result: Bool)->Void

//显示登录页面
func showLogin(controller: UIViewController? = nil, dismissHandle: AccountCompelteHandle? = nil) {
    let loginVC = LoginViewController.controller()
    let loginNavi = NavigationController.init(rootViewController: loginVC)
    loginVC.dismissHandle = { type in
        loginNavi.dismiss(animated: true, completion: {
            dismissHandle?(type)
        })
    }
    
    
    var vc = controller
    if controller == nil {
         vc = UIViewController.lsf_currentVC()
    }
    
    vc?.present(loginNavi, animated: true, completion: nil)
}


class LoginViewController: ViewController {

    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var mobileTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    
    @IBOutlet weak var loginBtn: UIButton!
    
    var dismissHandle: AccountCompelteHandle?
    
    static func controller(dismissHandle: AccountCompelteHandle? = nil) -> LoginViewController {
        let vc = LoginViewController.viewController(storyboardName: "Account") as! LoginViewController
        vc.dismissHandle = dismissHandle
        return vc
    }
    
   
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setPopRecognizerEnable(false)

        contentView.clipsToBounds = true
        contentView.layer.cornerRadius = 10.0
        contentView.layer.borderWidth = 0.5
        contentView.layer.borderColor = UIColor.lsf_color16(0x9c9c9c).cgColor
        
        loginBtn.clipsToBounds = true
        loginBtn.layer.cornerRadius = 10
        // Do any additional setup after loading the view.
        
        
        let mobileObserable: Observable<Bool> = mobileTextField.rx.text.orEmpty.map { text in
            var result = false
            result = (text.count == 11)
            return result
        }
        
        let passwordObserable: Observable<Bool> = passwordTextField.rx.text.orEmpty.map { text in
            var result = false
            result = (text.count >= 6 && text.count <= 20)
            return result
        }
        
        let ob = Observable.combineLatest(mobileObserable, passwordObserable) {$0 && $1}
        ob.subscribe(onNext: { (valid) in
            if valid{
                self.loginBtn.isEnabled = true
                self.loginBtn.backgroundColor = UIColor.lsf_color16(0xF56E77)
            }else{
                self.loginBtn.isEnabled = false
                self.loginBtn.backgroundColor = UIColor.lightGray
            }
        }).disposed(by: disposeBag)
      
        
        //登录
        loginBtn.rx.tap.bind {
            let mobile = self.mobileTextField.text!
            let password = self.passwordTextField.text!
            startAnimating()
            AccountService.login(mobile, password: password, success: { [weak self] (account) in
                stopAnimating()
                if let strongSelf = self {
                    strongSelf.dismissHandle?(true)
                }
                }, failure: { [weak self] (code, msg) in
                    stopAnimating()
                    lsf_alert(msg, viewController:self)
            })
           
            }.disposed(by: disposeBag)
        
       
        //监听注册、修改密码成功回调
        _ = NotificationCenter.default.rx.notification(Notification.Name(LoginViewControllerNotification)).takeUntil(self.rx.deallocated).subscribe(onNext: { [weak self] (notification) in
            guard let strongSelf = self else { return }
            guard let type = notification.object as? LoginType else { return }
            switch type {
            case .changePsd:
                strongSelf.navigationController?.popToViewController(strongSelf, animated: true)
                break
                
            default:
                strongSelf.dismissHandle?(true)
            }
        })
        
        
    }
    

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func closeClick(_ sender: UIButton) {
        self.dismissHandle?(false)
    }
    
    @IBAction func forgetPasswordClick(_ sender: UIButton) {
        let vc = VerifyCodeViewController.controller(.changePsd)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func registClick(_ sender: UIButton) {
        let vc = VerifyCodeViewController.controller(.rigist)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
